<template>
    <el-form :model="form" ref="mform" :rules="rules"
             style="min-width:500px;" :label-width="formLabelWidth" size="mini"
             v-loading.fullscreen.lock="loading">
        <el-form-item label="角色名" prop="name">
            <el-input v-model="form.name" autocomplete="off" style="width:280px;"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
                <el-radio label="0">启用</el-radio>
                <el-radio label="1">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="" prop="status" label-width="20px">
            <div class="role-menu-wrap">
                <div class="role-menu-item">
                    <h6>选择菜单</h6>
                    <perfect-scrollbar
                        class="role-menu-tree"
                        :settings="{}">
                        <el-tree ref="menutree"
                                 class="menu-custom-tree"
                                 :data="items"
                                 :show-checkbox="true"
                                 :check-strictly="true"
                                 node-key="tid"
                                 :highlight-current="true"
                                 :default-expanded-keys="expandedKeys"
                                 :default-checked-keys="checkedKeys"
                                 :props="treeSetting"
                                 @node-click="handleClick">
                            <!--<span class="role-custom-tree-node" slot-scope="{ node, data }">
                                <span>{{ data.name }}-{{data.tid}}</span>
                            </span>-->
                        </el-tree>
                    </perfect-scrollbar>
                </div>
                <div class="role-menu-item" style="width: 620px;margin-right: 0px;">
                    <h6 v-if="currentMenu && currentMenu.content_type === 'GROUP'">
                        <template v-if="currentMenu && currentMenu.name">
                            <b>“{{currentMenu.name}}”</b>
                        </template>分组下内容的操作与数据权限：
                    </h6>
                    <h6 v-else-if="currentMenu">
                        <b>“{{currentMenu.name}}”</b>内容视图：
                    </h6>
                    <div class="role-menu-actions" v-if="currentMenu && currentMenu.content_type === 'GROUP'">
                        <el-checkbox-group v-model="currentMenu.actions" size="small">
                            <template v-if="currentMenu.content_type === 'GROUP' && currentMenu.sys_rank != 'SYSTEM'">
                                <el-checkbox :label="ga.code" v-for="ga in groupActions"
                                             v-has="{
                                                type: 'GROUP',
                                                code: currentMenu.group_id,
                                                action: ga.code
                                             }">{{ga.name}}
                                </el-checkbox>
                            </template>
                            <!--<template v-else-if="currentMenu.content_type === 'CONTENT'">
                                <template v-if="currentMenu.type == 'list'">
                                    <el-checkbox :label="ga.code" v-for="ga in contentActions"
                                                 v-has="{
                                                type: 'CONTENT',
                                                code: currentMenu.content_id,
                                                action: ga.code
                                             }">{{ga.name}}
                                    </el-checkbox>
                                </template>
                                <template v-else>
                                    <el-checkbox :label="ga.code" v-for="ga in contentSingleActions"
                                                 v-has="{
                                                type: 'CONTENT',
                                                code: currentMenu.content_id,
                                                action: ga.code
                                             }">{{ga.name}}
                                    </el-checkbox>
                                </template>
                            </template>-->
                        </el-checkbox-group>
                    </div>
                    <div class="role-menu-views" v-if="currentMenu && currentMenu.views">
                        <div class="view" :class="{ 'active': v.form_view_id == currentMenu.view_id }"
                             v-for="v in currentMenu.views" @click="handleSelectView(v)">
                            <h5>{{v.view_name}}【{{v.form_view_code}}】</h5>
                            <i class="el-icon-check"></i>
                        </div>
                    </div>
                </div>
            </div>
        </el-form-item>

        <el-form-item label-width="0px" style="text-align: center;">
            <el-button type="primary" @click="submit()">确 定</el-button>
            <el-button @click="close()">取 消</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
    import { mapState, mapActions } from 'vuex';
    import axios from 'axios';
    import moment from 'moment';

    export default {
        props: [ 'show', 'modId' ],
        data() {
            return {
                formLabelWidth: '80px',
                winName: '新增',
                items: [],
                loading: false,
                currentMenu: {},

                form: {
                    name: '',
                    status: "0",
                },
                rules: {
                    name: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ]
                },
                expandedKeys: [],
                checkedKeys: [],
                treeSetting: {
                    children: 'subs',
                    label: 'name',
                    'icon-class': 'hello-icon'
                },
                actions: [],
                access: [],
                selectedMenus: [],

                opers: [
                    { value: 'between', label: '区间' },
                    { value: 'gt', label: '大于' },
                    { value: 'lt', label: '小于' },
                ],
                groupActions: [
                    { code: 'DIRADD', name: '新建文件夹' },
                    { code: 'DIRMOD', name: '文件夹重命名' },
                    { code: 'DIRDEL', name: '删除文件夹' },
                    { code: 'ADD', name: '新增内容' },
                    { code: 'MOD', name: '修改内容' },
                    { code: 'DEL', name: '删除内容' },
                    { code: 'CLONE', name: '复制内容' },
                ],
                contentActions: [
                    { code: 'VIEW', name: '查看' },
                    { code: 'ADD', name: '新增' },
                    { code: 'MOD', name: '修改' },
                    { code: 'DEL', name: '删除' },
                    { code: 'DL', name: '下载' },
                    { code: 'IMP', name: '导入' },
                ],
                contentSingleActions: [
                    { code: 'VIEW', name: '查看' },
                    { code: 'MOD', name: '修改' },
                ],
            }
        },
        components: {

        },
        created: function () {
            // this.pid = this.$route.query.pid;
        },
        mounted: function () {
            this.init();
        },
        watch: {
            '$route' (to, from) {
                // this.groupId = this.$route.params.groupId;
                // this.refresh();
            },
            'show'(val) {

                // console.log("role create show change ... ", val);
                if(val) {
                    this.init();
                }
            },
            'selectedMenus'(val) {
                // console.log(`======> selectedMenus: ` + val);
            }
        },
        filters: {
            typeRuleLabel(it) {

                if(it.type === 'checkbox') {
                    return "包含";
                } else if(it.type === 'radio') {
                    return "等于";
                } else {
                    return "区间";
                }
            },
            formItemLabel(it, currentMenu) {
                let name = "";

                if(currentMenu && currentMenu.form_items) {
                    for(let i = 0; i < currentMenu.form_items.length; i++) {
                        let fi = currentMenu.form_items[i];

                        if(fi && fi.name == it.name) {
                            name = fi.label;
                            break;
                        }
                    }
                }

                return name;
            },
        },
        computed: mapState([
            /*'mainMenu',
             'menuHide'*/
            'loginUser'
        ]),
        methods: {
            ...mapActions([
            ]),
            async init() {
                this.form.id = null;
                this.form.name = '';
                this.form.status = "0";

                if(this.modId) {
                    this.$refs.mform && this.$refs.mform.resetFields();

                    let data = await this.$japi.role.getRole(this.modId);

                    if(data) {
                        this.form = data;
                        this.items = data.menutree && data.menutree.items;
                        this.checkedKeys = data.menutree && data.menutree.selected;
                        this.refreshData();
                    }
                } else {
                    let data = await this.$japi.role.getRoleTree();

                    if(data) {
                        this.items = data.items;
                        this.checkedKeys = data.selected;
                        this.refreshData();
                    }
                }
            },
            refreshData() {

                if(this.items && this.items.length) {
                    for(let i = 0; i < this.items.length; i++) {
                        let it = this.items[i];
                        this.expandedKeys.push(it.tid);
                    }
                }

            },
            submit() {

                this.$refs.mform.validate((valid) => {
                    if (valid) {
                        this._submit();
                    } else {
                        return false;
                    }
                });
            },
            async _submit() {
                let url;
                let param = {
                    name: this.form.name,
                    status: this.form.status,
                    // items: this.$refs.menutree.getCheckedKeys()
                };
                let items = [];
                let selectedNodes = _.cloneDeep(this.$refs.menutree.getCheckedNodes());

                if(selectedNodes && selectedNodes.length) {
                    for(let i = 0; i < selectedNodes.length; i++) {

                        let selNode = selectedNodes[i];
                        items.push({
                            id: _.get(selNode, "tid"),
                            actions: _.get(selNode, "actions", []).join(","),
                            data_filter: JSON.stringify(_.get(selNode, "data_filter")),
                            view_id: _.get(selNode, 'view_id', -1)
                        });
                    }
                }
                param.items = items;

                let ret = null;

                this.loading = true;
                if(this.modId && this.form.id) {
                    param.id = this.form.id;
                    ret = await this.$japi.role.updateRole(param);
                } else {
                    ret = await this.$japi.role.createRole(param);
                }

                this.loading = false;

                if(ret) {
                    this.close(true);
                    this.$message('操作成功！');
                }
            },
            close(flag) {
                this.$emit('close', flag);
            },
            handleClick(data, node, ele) {

                /*if(!data.actions) {
                    this.$set(data, 'actions', []);
                }*/
                this.currentMenu = data;

                if(!_.get(this.currentMenu, 'actions')) {
                    this.$set(this.currentMenu, 'actions', []);
                }

                /*if(!_.get(this.currentMenu, 'data_filter')) {
                    this.$set(this.currentMenu, 'data_filter', {
                        _user_id: 'ALL',
                        _create_time: {
                            rang_type: 'none',  // none-不限，relative-相对时间，absolute-绝对时间
                            oper: 'between',
                            lte: 20,
                            gte: 20,
                            min: moment().format('YYYY-MM-DD HH:mm:ss'),
                            max: moment().format('YYYY-MM-DD HH:mm:ss'),
                        },
                        access: []
                    });
                }

                if(!_.get(this.currentMenu, 'data_filter.access')) {
                    this.$set(this.currentMenu.data_filter, 'access', []);
                }*/

                /*if(!_.get(this.currentMenu, 'form_items')) {
                    this.loadFormItems(this.currentMenu);
                } else {
                    this.setCanFilterProp(this.currentMenu);
                }*/

                if(!_.get(this.currentMenu, 'form')) {
                    this.loadFormViews(this.currentMenu);
                }

                // console.log(data, node, ele);
            },
            setCanFilterProp(data) {

                let filter = _.get(data, "data_filter");
                let access = _.get(filter, "access", []);
                let items = _.get(data, "form_items");

                if(!data || !data.content_id || !items || !filter) {
                    return;
                }

                for(let i = 0; i < items.length; i++) {

                    let fi = items[i];
                    let hasProp = false;

                    // radio, checkbox, time 三种可设置
                    if(_.indexOf(['radio', 'checkbox', 'time', 'date', 'datetime'], fi.type) >= 0) {
                        for(let j = 0; j < access.length; j++) {
                            let ai = access[j];

                            if(ai.name == fi.name) {
                                hasProp = true;
                                break;
                            }
                        }

                        if(!hasProp) {
                            let nac = {
                                name: fi.name,
                                enable: false,
                                type: fi.type
                            };

                            if(fi.type == 'checkbox') {
                                nac.in = [];
                            } else if(fi.type == 'radio') {
                                nac.eq = null;
                            } else {
                                nac.rang_type = 'none';
                                nac.oper = 'between';
                                nac.lte = 30;
                                nac.gte = 30;
                                nac.min = moment().format('YYYY-MM-DD HH:mm:ss');
                                nac.max = moment().format('YYYY-MM-DD HH:mm:ss');
                            }
                            access.push(nac);
                        }
                    }
                }

                this.$set(this.currentMenu.data_filter, "access", access);

                // console.log("================>>>>>> ", data);
            },
            loadFormItems(data) {

                let self = this;

                if(!data || !data.content_id) {
                    return;
                }

                this.loading = true;
                axios.get(`/web/api/content/get`, {
                    params: {
                        id: data.content_id,
                        hasForm: true
                    }
                })
                .then(({ data }) => {
                    if(data.code === 200 && data.data) {

                        let items = _.get(data, 'data.form.items');
                        self.$set(self.currentMenu, 'form_items', items);
                        self.setCanFilterProp(self.currentMenu);
                        self.loading = false;
                    }
                })
                .catch(function(e){
                    self.$message('加载数据失败，请稍后再试！');
                });
            },
            async loadFormViews(data) {
                if(!data || !data.form_id) {
                    return;
                }
                this.loading = true;

                let ret = await this.$japi.form.getFormViews(data.form_id);

                this.loading = false;

                if(ret) {
                    this.$set(this.currentMenu, 'views', ret);
                }
            },
            canSels(it, currentMenu) {

                let options = [];

                if(currentMenu && currentMenu.form_items) {
                    for(let i = 0; i < currentMenu.form_items.length; i++) {
                        let fi = currentMenu.form_items[i];

                        if(fi && fi.name == it.name) {
                            options = fi.options;
                            break;
                        }
                    }
                }

                return options;
            },
            handleSelectView(v) {
                this.currentMenu.view_id = v.form_view_id;
            },
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
    .role-menu-wrap {
        display: flex;

        .role-menu-item {
            margin-right:10px;

            h6 {
                font-size: 13px;
                color: #999;
                /*padding:10px;*/
                /*padding-bottom:5px;*/
                margin:0px;
                font-style: normal;
                font-weight:normal;
            }
            &.border {
                border: 1px solid #EEE;
            }
        }
        .role-menu-tree{
            height:350px;
            max-height: 500px;
            width:300px;
            overflow:auto;
            border: 1px solid #EEE;

            .role-custom-tree-node {
                .el-checkbox {
                    margin-right:5px;
                }
            }
        }
        .role-menu-actions {
            min-height:350px;
            border: 1px solid #EEE;
            padding: 5px 10px;
        }

        .role-menu-access {
            border-top: 1px solid #EEE;
            .disabled {
                color: #999;
            }
            .el-table .cell {
                padding-left:0px;
                padding-right:0px;
            }
        }
        .role-menu-label {
            font-size:12px;
            color: #CCC;
        }
    }

    .el-form .el-form-item {
        margin-bottom:10px;
    }
    .role-menu-access .el-form-item {
        margin-bottom:0px;

        .el-checkbox {
            margin-bottom:0px;
        }
    }
    .role-menu-views {
        .view {
            border: 1px solid #EEE;
            border-radius: 2px;
            margin-bottom: 5px;
            padding: 10px;
            position: relative;

            .el-icon-check {
                position: absolute;
                right: 10px;
                top: 50%;
                transform: translateY(-50%);
                color: #3a8ee6;
                display: none;
            }

            h5 {
                font-size: 13px;
                margin: 0px;
                cursor: pointer;
            }
            p {
                font-size: 12px;
                margin: 0px;
            }

            &:hover, &.active {
                border-color: #3a8ee6;
            }
            &.active {
                .el-icon-check {
                    display: block;
                }
            }
        }
    }
</style>
<style lang="scss">
    /*.role-menu-access {
        .el-table .cell {
            padding-left:5px;
            padding-right:5px;
        }
    }*/
</style>
